package com.itheima.health.controller;

import com.itheima.health.common.MessageConst;
import com.itheima.health.dao.Permission;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.User;
import com.itheima.health.service.UserService;
import com.itheima.health.vo.LoginParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Set;

/**
 * @author zhangmeng
 * @description
 * @date 2019/9/6
 **/
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    private static final String CURRENT_USER = "CURRENT_USER";
    @Autowired
    private UserService userService;

    @Autowired
    private Permission permission;

    /**
     * 根据用户名和密码登录
     *
     * @param request
     * @return
     */
    @PostMapping("/login")
    public Result login(HttpServletRequest request, @RequestBody LoginParam param) {
        log.info("[登录]data:{}",param);
        //rpc调用查询用户信息
        User user = userService.findByUsername(param.getUsername());
        //  判断用户是否存在
        if (null == user) {
            log.info("[登录]失败，user:{}",param.getUsername());
            return new Result(false, MessageConst.LOGIN_FAIL);
        }

        // 用户存在比对密码
        boolean pswFlag = checkPassword(param.getPassword(), user.getPassword());
        if (!pswFlag) { // 密码错误
            return new Result(false, MessageConst.LOGIN_FAIL);
        }

        //用户登录成功
        log.info("[登录]成功，user:{}",user.getUsername());
        // 设置Session
        // 1.获取当前用户的所有权限
        Set<String> permissions =  permission.getKeywordByUserId(user.getId());
        user.setPermissions(permissions);
        request.getSession().setAttribute("user", user);
        return new Result(true, MessageConst.LOGIN_SUCCESS);
    }



    @GetMapping("/logout")
    public Result logout(HttpServletRequest request){
        request.getSession().invalidate();
        return new Result(true, MessageConst.ACTION_SUCCESS);
    }

    /**
     * 比对密码
     * @param inputPassword 用户输入密码
     * @param originalPassword 数据库中查询到的密码
     * @return
     */
    private boolean checkPassword(String inputPassword, String  originalPassword) {
        // 判断加密方式
        if (originalPassword.startsWith("{md5}")) { // md5加密方式
            // 判断密码是否正确
            if (DigestUtils.md5DigestAsHex(inputPassword.getBytes()).equals(originalPassword.replace("{md5}", ""))) {// 密码正确
                return true;
            }
            // 密码错误
            return false;
        } else if (originalPassword.startsWith("{bcrypt}")) { // bcrypt加密方式
            // 判断密码是否正确
            if (DigestUtils.md5DigestAsHex(inputPassword.getBytes()).equals(originalPassword.replace("{bcrypt}", ""))) {// 密码正确
                return true;
            }
            // 密码错误
            return false;
        } else { // 没有进行加密
            // 判断密码是否正确
            if (inputPassword.equals(originalPassword)) { // 密码正确
                return true;
            }
            return false;
        }
    }

    /**
     * 获取用户名
     * @param request
     * @return
     */
    @GetMapping("/getUsername")
    public Result getUsername(HttpServletRequest request) {
        log.info("获取当前登录用户名字");
        User user = (User) request.getSession().getAttribute("user");
        return new Result(true, "查询成功", user.getUsername());
    }
}
